import os
import pathlib
import fileinput


def traverse_dir_files(root_dir, ext=None):
    """
    列出文件夹中的文件, 深度遍历
    :param root_dir: 根目录
    :param ext: 后缀名
    :param is_sorted: 是否排序，耗时较长
    :return: [文件路径列表, 文件名称列表]
    """
    names_list = []
    paths_list = []
    for path in list(pathlib.Path(root_dir).rglob("*")):
        path = str(path)
        name = path.split("/")[-1]
        if name.startswith('.') or "." not in name:  # 去除隐藏文件
            continue
        if ext:  # 根据后缀名搜索
            if name.endswith(ext):
                names_list.append(name)
                paths_list.append(path)
        else:
            names_list.append(name)
            paths_list.append(path)
    if not names_list:  # 文件夹为空
        return paths_list, names_list

    return paths_list, names_list


a = traverse_dir_files(r"C:\Users\liyuzheng\androidProject\starmaker-android-client", "build.gradle")


def read_gradle_file(path):
    with open(path, encoding='utf-8', mode="r") as fr:
        with open(path.replace(".gradle", ".bak"), encoding='utf-8', mode="w+") as fw:
            while True:
                line = fr.readline()
                if line:
                    # temp = line
                    str = build_setting(line)
                    fw.write(str)
                    # if temp.__contains__('implementation project'):
                    #     str = build_setting(temp)
                    #     fw.write(str)
                    # else:
                    #     fw.write(line)
                else:
                    break
    os.remove(path)
    os.rename(path.replace(".gradle", ".bak"), path)


def build_setting(str):
    line = str
    if str.__contains__('implementation project'):
        str = str.strip()
        start = int(str.find("'") + 1)
        end = int(len(str) - 2)
        str1 = str[start:end]
        str2 = str1[str1.rfind(":") + 1:len(str1)]
        module_name = str2.replace("_", "")

        str = str.replace("implementation", "releaseImplementation")
        print("---" + str)
        line = str.replace(str,
                           "\tdebugImplementation 'com.ushowmedia.starmaker:" + module_name + ":1.0.0'\n\t" + str + "\n\t")
        print(line)
        return line

    elif str.__contains__('api project'):
        str = str.strip()
        start = int(str.find("'") + 1)
        end = int(len(str) - 2)
        str1 = str[start:end]
        str2 = str1[str1.rfind(":") + 1:len(str1)]
        module_name = str2.replace("_", "")

        str = str.replace("api", "releaseApi")
        line = str.replace(str,
                           "debugApi 'com.ushowmedia.starmaker:" + module_name + ":1.0.0'\n\t" + str)
        print(line)
        return line
    return line


for r in a[0]:
    read_gradle_file(r)
